package com.ekuaitu.kuaitustaff.api;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.webkit.JavascriptInterface;

import com.ekuaitu.kuaitustaff.activity.LoginNewActivity;
import com.ekuaitu.kuaitustaff.activity.WebViewActivity;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.bean.ResultBean;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.Dialogs.ChooseAvatarDialog;
import com.ekuaitu.kuaitustaff.utils.Dialogs.DialogTwoButton;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.ble.BluetoothHelper;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import wendu.dsbridge.CompletionHandler;

/**
 * Created by michaelpi on 2018/3/14.
 */

public class JsApi {
    private Context mContext;
    private WebViewActivity webViewActivity;
    public File outputImage;
    private Uri imageUri;
    public CompletionHandler<Object> dsBridgeHandler;

    public JsApi(Context context) {
        this.mContext = context;
        this.webViewActivity = (WebViewActivity) context;
    }

    //Webview标题
    @JavascriptInterface
    public void modifyNativeNavBarTitle(Object msg, CompletionHandler<String> handler) {
        Logger.i("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        final String title = jsonObject.optString("title");
        Logger.i("jsbridgetitle", title);
        webViewActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewActivity.setTitle(title);
            }
        });
    }

    //联系客服
    @JavascriptInterface
    public void callphone(Object msg, CompletionHandler<String> handler) {
        Logger.i("jsbridge", msg.toString());
        final DialogTwoButton dialogTwoButton = new DialogTwoButton(mContext);
        dialogTwoButton.setTitle("提醒");
        dialogTwoButton.setMessage("确定要联系客服吗？");
        dialogTwoButton.setYesOnclickListener("联系客服", new DialogTwoButton.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + SPUtils.getInstance(mContext).getStringValue(SPKey.HOT_LINE)));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                dialogTwoButton.dismiss();
            }
        });

        dialogTwoButton.setNoOnclickListener("取消", new DialogTwoButton.onNoOnclickListener() {
            public void onNoClick() {
                dialogTwoButton.dismiss();
            }
        });
        dialogTwoButton.show();

    }

    //退出登录
    @JavascriptInterface
    public void logout(Object msg, CompletionHandler<String> handler) {
        Logger.i("jsbridge", msg.toString());
        SPUtils.getInstance(mContext).clearSharePreference();
        ((MyApplication) MyApplication.getInstance()).setUserId(null);
        ((MyApplication) MyApplication.getInstance()).setToken(null);
        ((MyApplication) MyApplication.getInstance()).setHeaderToken(null);
        BluetoothHelper.getInstance().unregisterBluetoothStateListener();
        Intent intent = new Intent(mContext, LoginNewActivity.class);
        mContext.startActivity(intent);
        AppManager.getAppManager().finishAllActivity();
    }

    //finish current page
    @JavascriptInterface
    public void dissmissCurrentVc(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        AppManager.getAppManager().finishActivity();
    }

    //车损提交成功
    @JavascriptInterface
    public void submitSucess(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge", msg.toString());
        EventBus.getDefault().post(new ResultBean());
        AppManager.getAppManager().finishActivity();
    }

    //获取图片
    @JavascriptInterface
    public void modelNativeChosePhotoController(Object msg, CompletionHandler<Object> handler) {
        Logger.d("jsbridge", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        String type = jsonObject.optString("type");
        //跳转图片选择
        dsBridgeHandler = handler;
        if (type.equals("parkingFee")) {
            choosePic();
        } else if (type.equals("breakage")) {
            checkperssionAndCamera();
        }
    }

    @JavascriptInterface
    public void setNativeCookie(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge wxAuth", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        SPUtils.getInstance(mContext).putStringValue(jsonObject.optString("key"), jsonObject.optString("value"));
    }


    @JavascriptInterface
    public String getNativeCookie(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return ((MyApplication) MyApplication.getInstance()).getCookieMap().get(msg.toString());
    }

    @JavascriptInterface
    public Map<String, String> getNativeCookies(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return ((MyApplication) MyApplication.getInstance()).getCookieMap();
    }

    @JavascriptInterface
    public void setNativePersistence(Object msg, CompletionHandler<String> handler) {
        Logger.d("jsbridge wxAuth", msg.toString());
        JSONObject jsonObject = (JSONObject) msg;
        SPUtils.getInstance(mContext).putStringValue(jsonObject.optString("key"), jsonObject.optString("value"));
    }

    @JavascriptInterface
    public String getNativePersistence(Object msg) {
        Logger.d("jsbridge", msg.toString());
        return SPUtils.getInstance(mContext).getStringValue(msg.toString());
    }

    private void choosePic() {
        ChooseAvatarDialog chooseAvatarDialog = new ChooseAvatarDialog(mContext);
        chooseAvatarDialog.setOnItemClickListener(new ChooseAvatarDialog.OnItemClickListener() {
            @Override
            public void onClickItem(int position) {
                chooseAvatarDialog.dismiss();
                if (position == 0) {
                    checkperssionAndCamera();
                } else if (position == 1) {
                    openAlbum();
                }
            }
        });
        chooseAvatarDialog.show();
    }

    private void openAlbum() {
        if (ContextCompat.checkSelfPermission(webViewActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(webViewActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            Intent intent = new Intent("android.intent.action.GET_CONTENT");
            intent.setType("image/*");
            webViewActivity.startActivityForResult(intent, Constants.REQUEST_ALBUM);//打开相册
        }
    }

    public void checkperssionAndCamera() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(webViewActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(webViewActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }
            if (!permissionLists.isEmpty()) {//有拒绝的权限
                ActivityCompat.requestPermissions(webViewActivity, permissionLists.toArray(new String[permissionLists.size()]), Constants.PERMISSION_REQUEST_CAMERA);
            } else {
                takePhoto();
            }
        } else {
            takePhoto();
        }
    }

    private void takePhoto() {
        // 创建File对象，用于存储拍照后的图片
        outputImage = new File(mContext.getExternalCacheDir(), "outjs_image.jpg");
        Logger.i("图片", mContext.getExternalCacheDir() + "");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT < 24) {
            imageUri = Uri.fromFile(outputImage);
        } else {
            imageUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", outputImage);
        }
        // 启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        webViewActivity.startActivityForResult(intent, Constants.REQUEST_CAMERA);
    }
}